﻿using Project.Net.Application;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Project.Net.Inra.Redis
{
    public class RedisDistributedLock : IDisposable
    {
        private readonly IRedisRepository _redisRepository;
        private readonly string _key;
        private readonly string _value;
        private bool _isAcquired;

        public RedisDistributedLock(IRedisRepository redisRepository, string key, string value)
        {
            _redisRepository = redisRepository;
            _key = key;
            _value = value;
        }
        /// <summary>
        /// 异步尝试获取锁，并设置过期时间
        /// </summary>
        /// <param name="expireTime"></param>
        /// <returns></returns>
        public async Task<bool> LockAsync(TimeSpan expireTime)
        {
            _isAcquired = await _redisRepository.SetAddAsync(_key, _value);
            if (_isAcquired)
            {
                await _redisRepository.ExpireKeyAsync(_key, expireTime);
            }
            return _isAcquired;
        }
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            if (_isAcquired)
            {
                _redisRepository.DeleteKeyAsync(_key);
            }
        }
    }
}
